/**
 * Created by mkDark on 2018/3/23.
 */
var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxMemberModel = function (obj) {
    YjxBaseModel.call(this,obj);

  //  `member_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '会员id',
  //`user_id` bigint(20) NOT NULL COMMENT '用户id',
  //`vip` int(2) NOT NULL DEFAULT '10' COMMENT '0:无,10:普通vip会员',
  //`desc` text COMMENT '备注',
  //`expiry_time` datetime NOT NULL COMMENT '有效截止日期',
  //`last_expiry_time` datetime DEFAULT NULL COMMENT '上一次有效截止日期的历史纪录',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',
  //      PRIMARY KEY (`member_id`)
  //  ) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8 COMMENT='一键秀会员表'

};

YjxMemberModel.prototype = new YjxBaseModel();

// 取得表名
YjxMemberModel.prototype.getTableName = function(){
    return 'yjx_member';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxMemberModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'member_id='+this.member_id;
};


/**
 * 查找vip会员信息
 * @author xc
 * @param userId 用户唯一标识
 * @param callback
 */
YjxMemberModel.prototype.findVipMember = function(userId, callback){

    pool.pool.getConnection(function(err, connection) {
        // 链接出错
        if(err){
            console.log('YjxMemberModel [findVipMember] getConnection err:' + err);
            return callback(err, null);
        }

        var sql  =  " SELECT m.*, "+
            " CASE WHEN m.expiry_time>sysdate() THEN 1 ELSE 0 END AS validFlg, " +
            " DATE_FORMAT(m.expiry_time, '%Y-%m-%d %H:%i:%S') AS str_expiry_time "+
            " FROM yjx.yjx_user u, " +
            "      yjx.yjx_member m " +
            " WHERE u.user_id= " + userId +
            "   AND u.del_flg=0 " +
            "   AND m.user_id=u.user_id " +
            "   AND m.vip=10 " +
            "   AND m.del_flg=0 ";
        console.log(sql);
        connection.query(sql, function(error, result) {
            connection.release();
            if(error){
                console.log('YjxMemberModel [findVipMember] query err: ' + error);
            }
            if(result && result.length > 0){
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }

        });
    });
};

/**
 * 新建vip会员
 * @author xc
 * @param userId
 * @param stTime: 有效开始日期 'yyyy-mm-dd HH:MM:SS'
 * @param unit: 单位 1(年), 2(季), 3(月), 4(周), 5(天), 默认单位为3(月)
 * @param qty: 对应数量: 年数, 季度数, 月数, 周数, 天数
 * @param callback
 */
YjxMemberModel.prototype.createVipMember = function(userId, stTime, unit, qty, callback){

    pool.pool.getConnection(function(err, connection) {
        // 链接出错
        if(err){
            console.log('YjxMemberModel [createVipMember] getConnection err:' + err);
            return callback(err, null);
        }

        var expStart = 'now()';
        if(stTime && stTime.length>0) {
            expStart = '"'+stTime+'"';
        }

        var sql = ' INSERT INTO yjx.yjx_member '+
            ' SET user_id='+userId+
            ' ,vip=10 '+
            ' ,create_time=sysdate(), update_time=sysdate(), del_flg=0 '+
            ' ,update_by='+userId;
        if(unit==1) {// 年
            sql += ' ,`desc`="[Vip_New:'+Number(qty||'0')+'Year]" '+
            ' ,expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' YEAR) ';
        } else if(unit==2) {// 季度
            sql += ' ,`desc`="[Vip_New:'+Number(qty||'0')+'Qtr]" '+
            ' ,expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' QUARTER) ';
        } else if(unit==4) {// 周
            sql += ' ,`desc`="[Vip_New:'+Number(qty||'0')+'Week]" '+
            ' ,expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' WEEK) ';
        } else if(unit==5) {// 天
            sql += ' ,`desc`="[Vip_New:'+Number(qty||'0')+'Day]" '+
            ' ,expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' DAY) ';
        } else {// 默认月
            sql += ' ,`desc`="[Vip_New:'+Number(qty||'0')+'Month]" '+
            ' ,expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' MONTH) ';
        }

        console.log(sql);
        connection.query(sql, function(error, result) {
            connection.release();
            if(error) {
                console.log(error);
            }
            callback(error, result.insertId);

        });
    });
};

/**
 * 更新vip会员有效期
 * @author xc
 * @param userId(必填): 用户id
 * @param memberId(可选): 会员id
 * @param unit(可选): 单位 1(年), 2(季), 3(月), 4(周), 5(天), 默认单位为3(月)
 * @param qty(必填): 对应数量(可为负数): 年数, 季度数, 月数, 周数, 天数
 * @param reset(必填): 0直接在原截止期上累加, 1重新计算截止期(开始日时为当前时间), 2重新计算截止期(开始日时为stTime)
 * @param stTime(可选): 有效开始日期 'yyyy-mm-dd HH:MM:SS'
 * @param callback
 */
YjxMemberModel.prototype.updVipMemberExpTime = function(userId, memberId, unit, qty, reset, stTime, callback){

    pool.pool.getConnection(function(err, connection) {
        // 链接出错
        if(err){
            console.log('YjxMemberModel [updVipMemberExpTime] getConnection err:' + err);
            return callback(err, null);
        }

        var expStart = 't.expiry_time';
        if(reset==1) {
            expStart = 'now()';
        } else if(reset==2 && stTime && stTime.length>0) {
            expStart = '"'+stTime+'"';
        }

        var sql = ' UPDATE yjx.yjx_member t '+
            ' SET t.last_expiry_time=t.expiry_time ' +
            ' ,t.update_time=sysdate() ' +
            ' ,t.update_by='+userId;

        if(unit==1) {// 年
            sql += ' ,t.desc= concat(IFNULL(t.desc,"")," # [Vip_Upd:'+Number(qty||'0')+'Year]") '+// 拼接之前的desc
            ' ,t.expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' YEAR) ';
        } else if(unit==2) {// 季度
            sql += ' ,t.desc= concat(IFNULL(t.desc,"")," # [Vip_Upd:'+Number(qty||'0')+'Qtr]") '+// 拼接之前的desc
            ' ,t.expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' QUARTER) ';
        } else if(unit==4) {// 周
            sql += ' ,t.desc= concat(IFNULL(t.desc,"")," # [Vip_Upd:'+Number(qty||'0')+'Week]") '+// 拼接之前的desc
            ' ,t.expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' WEEK) ';
        } else if(unit==5) {// 天
            sql += ' ,t.desc= concat(IFNULL(t.desc,"")," # [Vip_Upd:'+Number(qty||'0')+'Day]") '+// 拼接之前的desc
            ' ,t.expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' DAY) ';
        } else {// 默认月
            sql += ' ,t.desc= concat(IFNULL(t.desc,"")," # [Vip_Upd:'+Number(qty||'0')+'Month]") '+// 拼接之前的desc
            ' ,t.expiry_time=date_add('+expStart+', INTERVAL '+Number(qty||'0')+' MONTH) ';
        }

        sql += ' WHERE t.del_flg=0 AND t.vip=10 AND t.user_id='+userId;
        if(memberId>0) {
            sql += ' AND t.member_id='+memberId;
        }

        console.log(sql);
        connection.query(sql, function(error, result) {
            connection.release();

            if(error) {
                console.log(error);
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 获取用户vip信息
 *
 * @author 毛凯
 * @date   2018-3-23
 *
 * @param userId 用户唯一标识
 * @param callback vip信息
 * */
YjxMemberModel.prototype.getVipInfo = function (userId,callback) {
    pool.pool.getConnection(function(connectErr, connection) {
        if (connectErr) {
            console.log('YjxMemberModel.getNotifications Err:'+connectErr);
            return callback(connectErr, null);
        }
        var sql ="	SELECT	" +
            "	  UNIX_TIMESTAMP(mb.expiry_time) AS expiryTimeStamp,	" +
            "	  DATE_FORMAT(mb.expiry_time, '%Y-%m-%d') AS expiryTime,	" +
            "	  IF(DATEDIFF(DATE_FORMAT(mb.expiry_time, '%Y-%m-%d'),DATE_FORMAT(NOW(), '%Y-%m-%d')) > 0,1,0) AS isVip,	" +
            "	  DATEDIFF(	" +
            "	    DATE_FORMAT(mb.expiry_time, '%Y-%m-%d'),	" +
            "	    DATE_FORMAT(NOW(), '%Y-%m-%d')	" +
            "	  ) AS expireDayNum,	" +
            "	  mb.vip AS `level`	" +
            "	FROM	" +
            "	  yjx.yjx_member AS mb	" +
            "	WHERE mb.user_id = "+userId+"	" +
            "	  AND mb.del_flg = 0	" ;
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            // And done with the connection.
            connection.release();
            if(queryErr || result.length <= 0) {
                return callback(queryErr, null);
            }
            return callback(queryErr,result[0]);
        });
    });
};



module.exports = YjxMemberModel;

